package cn.cat.gitee.utils;

import eu.bitwalker.useragentutils.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import sun.management.resources.agent;

import java.util.HashMap;
import java.util.Map;

public class UserAgentUtil {

    private static UserAgentAnalyzer userAgentAnalyzer = UserAgentAnalyzer.newBuilder().withAllFields().build();

    //private UserAgent userAgent;



    public UserAgentUtil() {

        //this.userAgentAnalyzer = UserAgentAnalyzer.newBuilder().withAllFields().build();
    }

    public static Map<String,String> parseOSAndBrowser(int type,String agent){
        if (agent==null || "".equals(agent)) {
            return null;
        }

        if (type==1) {
            return getUserAgentByNL(agent);
        }else {
            return getUserAgentByEU(agent);
        }

    }

    public static Map<String,String> getUserAgentByEU(String agent){
        Map<String, String> hashMap = new HashMap<>();
        UserAgent userAgent = UserAgent.parseUserAgentString(agent);
        String browsername = userAgent.getBrowser().getName();
        String osname = userAgent.getOperatingSystem().getName();
        String devicetype = userAgent.getOperatingSystem().getDeviceType().getName();
        hashMap.put("browsername", browsername);
        hashMap.put("osname", osname);
        hashMap.put("devicetype", devicetype);
        return hashMap;
    }

    public static Map<String,String> getUserAgentByNL(String agent){
        Map<String, String> hashMap = new HashMap<>();
        nl.basjes.parse.useragent.UserAgent.ImmutableUserAgent immutableUserAgent = userAgentAnalyzer.parse(agent);
        String browsername = immutableUserAgent.getValue("AgentName");
        String osname = immutableUserAgent.getValue("OperatingSystemName");
        String devicetype = immutableUserAgent.getValue("OperatingSystemClass");
        hashMap.put("browsername", browsername);
        hashMap.put("osname", osname);
        hashMap.put("devicetype", devicetype);
        return hashMap;
    }
}
